<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2017/6/23
 * Time: 14:02
 */

namespace Servers;

class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new \swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 4,  // 指定启动的worker进程数。建议开启的worker进程数为cpu核数的1-4倍。
            'daemonize' => false,
            'max_request' => 10000, // worker进程允许处理的最大任务数。 说明：设置该值后，每个worker进程在处理完max_request个请求后就会自动重启。设置该值的主要目的是为了防止worker进程处理大量请求后可能引起的内存溢出。
            'dispatch_mode' => 2,
            'debug_mode'=> 1,

        ));

        // 第二数组参数[当前类， 当前类的方法]
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));

        $this->serv->start();
    }

    public function onStart(\swoole_server  $serv ) {
        echo "Start\n\n";
    }

    /**
     * 监听链接进入事件
     * @param $serv      \Swoole\Server对象
     * @param $fd        客户端链接的唯一标识，自增id; 是连接的文件描述符，发送数据/关闭连接时需要此参数
     * @param $reactorId TCP连接所在的Reactor线程ID
     */
    public function onConnect(\swoole_server $serv, $fd, $reactorId ) {
        echo "connect\n\n";
        $serv->send( $fd, "reactorId = {$reactorId}, message = connect, fd = {$fd} \n\n" );
    }

    /**
     * 收到消息
     * @param \swoole_server $serv
     * @param $fd
     * @param $from_id
     * @param $data 客户端发送的数据
     */
    public function onReceive( \swoole_server $serv, $fd, $reactorId, $data ) {
        echo "receive:{$data} \n\n";
        $serv->send($fd, "receive client: {$data}");
    }

    public function onClose(\swoole_server $serv, $fd, $reactorId ) {
        echo "Client {$fd} close connection\n\n";
    }
}
// 启动服务器
$server = new Server();